package com.example.controller;

import com.example.service.AIService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/api/question")
public class QuestionController {

    @Autowired
    private AIService aiService;

    @GetMapping("/query")
    public Map<String, Object> queryQuestionGet(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String options,
            @RequestParam(required = false) String type) {
        
        System.out.println("\n=== 收到 GET 请求 ===");
        System.out.println("原始参数：");
        System.out.println("title: " + title);
        System.out.println("options: " + options);
        System.out.println("type: " + type);
        
        // 解码参数
        title = decodeParameter(title);
        options = decodeParameter(options);
        type = decodeParameter(type);
        
        System.out.println("\n解码后参数：");
        System.out.println("title: " + title);
        System.out.println("options: " + options);
        System.out.println("type: " + type);
        
        return processQuestion(title, options, type);
    }

    @PostMapping("/query")
    public Map<String, Object> queryQuestionPost(@RequestBody Map<String, String> request) {
        System.out.println("\n=== 收到 POST 请求 ===");
        System.out.println("请求体：");
        System.out.println(request);
        
        return processQuestion(
            request.get("title"),
            request.get("options"),
            request.get("type")
        );
    }

    private Map<String, Object> processQuestion(String title, String options, String type) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 构建问题
            String question = String.format("题目：%s\n类型：%s\n选项：%s", 
                title != null ? title : "无题目", 
                type != null ? type : "无类型",
                options != null ? options : "无选项");
            
            System.out.println("\n发送给 AI 的问题：");
            System.out.println(question);
            
            // 获取 AI 响应
            String aiResponse = aiService.getAIResponse(question);
            System.out.println("\nAI 响应：");
            System.out.println(aiResponse);
            
            // 设置响应
            if (aiResponse != null && !aiResponse.isEmpty()) {
                Map<String, Object> data = new HashMap<>();
                data.put("question", title);
                
                // 根据题目类型处理答案
                if ("multiple".equals(type)) {
                    // 多选题，将答案用#分隔，并确保格式正确
                    String answer = aiResponse.trim();
                    // 如果答案包含逗号，先替换为#
                    answer = answer.replaceAll("[,，]", "#");
                    // 去除空格
                    answer = answer.replaceAll("\\s+", "");
                    data.put("answer", answer);
                } else if ("judgement".equals(type)) {
                    // 判断题，转换为布尔值
                    data.put("answer", aiResponse.contains("正确") || aiResponse.contains("对") ? "true" : "false");
                } else if ("fill".equals(type) || "answer".equals(type) || "completion".equals(type)) {
                    // 填空题、解答题和完成题直接使用答案
                    data.put("answer", aiResponse.trim());
                } else {
                    // 单选题直接使用答案
                    data.put("answer", aiResponse.trim());
                }
                
                data.put("times", 1);
                
                response.put("code", 1);
                response.put("data", data);
                response.put("message", "请求成功");
            } else {
                response.put("code", 0);
                response.put("message", "未找到答案");
            }
            
            System.out.println("\n返回的响应：");
            System.out.println(response);
            System.out.println("\n=== 请求处理完成 ===\n");
            
        } catch (Exception e) {
            System.out.println("\n发生错误：");
            e.printStackTrace();
            
            response.put("code", 0);
            response.put("msg", "调用 AI 服务失败：" + e.getMessage());
        }
        
        return response;
    }

    private String decodeParameter(String param) {
        if (param == null) {
            return null;
        }
        try {
            return URLDecoder.decode(param, StandardCharsets.UTF_8.name());
        } catch (Exception e) {
            return param;
        }
    }
} 